package controllers

import (
	"github.com/ArtisanCloud/PowerWeChat/v3/src/miniProgram"
	"github.com/gin-gonic/gin"
	"social-app/models"
	"social-app/pkg/err_msg"
	"social-app/pkg/jwt_token"
	"social-app/pkg/response"
	"social-app/pkg/wechat"
	"time"
)

type WeChatController struct {
	WechatApp      *miniProgram.MiniProgram
	WechatAppError error
}

func (weChatController *WeChatController) weChatInit() {
	weChatController.WechatAppError = wechat.MiniProgramAppError
	weChatController.WechatApp = wechat.MiniProgramApp
	if weChatController.WechatAppError != nil {
		panic("wechat App Error: " + weChatController.WechatAppError.Error())
	}
}

func (weChatController *WeChatController) Login(c *gin.Context) {
	type reqParams struct {
		WxCode string `json:"wx_code" binding:"required"`
	}
	var params reqParams
	if err := c.ShouldBind(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, nil))
	}
	weChatController.weChatInit()
	resp, err := weChatController.WechatApp.Auth.Session(c, params.WxCode)
	if err != nil {
		panic("Get User OpenId Error: " + err.Error())
	}
	OpenId := resp.OpenID
	if OpenId == "" {
		panic("Get User OpenId Fail")
	}
	user, _ := models.GetUserByOpenId(OpenId)
	type respParams struct {
		Token  string `json:"token"`
		OpenId string `json:"openid"`
	}
	respData := respParams{
		OpenId: OpenId,
	}
	if user.Id > 0 {
		respData.Token, err = jwt_token.Encode(jwt_token.User{
			UserId:   user.Id,
			Username: user.Username,
			Time:     time.Now(),
		})
		if err != nil {
			panic("JWT Encode User Error: " + err.Error())
		}
	}
	response.Success(c, "获取登录信息成功", respData)
}
